<?php
/**                                          
 * 私信
 * @author M2
 * @version 1.0
 * create Date 2013-04-27
 */
class MessageModel extends Model{
    protected $tableName = 'message_content';
    /**
     * 私信内容列表
     *
     * @param int     $list_id      私信列表ID
     * @param int     $uid          用户ID
     * @param int     $since_id     最早会话ID
     * @param int     $lastest_id   最新会话ID
     * @param string  $load         加载方式 new：最新会话 old：之前会话
     * @param int     $count        旧会话加载条数
     * @return array
     */
    public function getMessageByListId($list_id, $uid, $since_id = null, $max_id = null, $count = 20) {
        $list_id  = intval($list_id);
        $uid      = intval($uid);
        $since_id = intval($since_id);
        $max_id   = intval($max_id);
        $count    = intval($count);
        // 验证该用户是否为该私信成员
        if (!$list_id || !$uid || !$this->isMember($list_id, $uid, false)) {
            return false;
        }
        $where = "`list_id`={$list_id} AND (is_del=0 OR is_del !={$uid})";
        if ($since_id > 0) {
            $where .= " AND `message_id`>{$since_id}";
            $limit  = null;
        } else {
            $max_id > 0 && $where .= " AND `message_id`<{$max_id}";
            // 多查询一条验证，是否还有后续信息
            $limit = intval($count) + 1;
        }
        $res['data']  = M('message_content')->where($where)->order('message_id DESC')->limit($limit)->select();
        $res['count'] = count($res['data']);
        foreach($res['data'] as $k=>$v){
            $res['data'][$k]['content'] = common('Html')->text($v['content']);
        }
        if ($since_id > 0) {
            $res['since_id'] = $res['data'][0]['message_id'];
            $res['max_id']   = $res['data'][$res['count'] - 1]['message_id'];
        } else {
            $res['since_id'] = $res['data'][0]['message_id'];
            // 结果数等于查询数，则说明还有后续message
            if ($res['count'] == $limit) {
                // 去除结果的最后一条
                array_pop($res['data']);
                // 计数减一
                $res['count'] --;
                // 取最后一条结果message_id
                $res['max_id'] = $res['data'][$res['count'] - 1]['message_id'];
            } else if ($res['count'] < $limit) {
                // 取最后一条结果message_id设置为0，表示结束
                $res['max_id'] = 0;
            }
        }
        return $res;
    }
    
    /**
     * 发送私信
     *
     * @param array $data     私信信息,包括to接受对象、title私信标题、content私信正文
     * @param int   $from_uid 发送私信的用户ID
     * @return array          返回新添加的私信的ID
     */
    public function postMessage($data, $from_uid) {
        $from_uid = intval($from_uid);
        $data['to']       = is_array($data['to']) ? $data['to'] : explode(',', $data['to']);
        // 私信成员
        $data['member']   = array_filter(array_merge(array($from_uid), $data['to']));
        // 发起时间
        $data['mtime'] = time();
        // 添加或更新私信list
        if (false == $data['list_id'] = $this->_addMessageList($data, $from_uid)) {
            return false;
        }
        // 存储私信成员
        if (false === $this->_addMessageMember($data, $from_uid)) {
            return false;
        }
        // 存储内容
        if (false == $this->_addMessage($data, $from_uid)) {
            return false;
        }
        return $data['list_id'];
    }

    /**
     * 回复私信
     *
     * @param int    $id         回复的私信list_id
     * @param string $content    内容
     * @param int    $from_uid   回复者
     * @return mixed 回复失败返回false，回复成功返回本条新回复的message_id
     */
    public function replyMessage($list_id, $content, $from_uid) {
        if (!$this->isMember($list_id, $from_uid, false)) {
            return false;
        }
        $list_id  = intval($list_id);
        $from_uid = intval($from_uid);
        $time = time();
        // 添加新记录
        $data['list_id']  = $list_id;
        $data['content']  = $content;
        $data['mtime']    = $time;
        $new_message_id = $this->_addMessage($data, $from_uid);
        unset($data);
        if ( !$new_message_id ) {
            return false;
        }else {
            $list_data['list_id']       = $list_id;
            $list_data['last_message'] = serialize(array(
                'from_uid' => $from_uid,
                'content'  => common('String')->keyWordFilter(common('Html')->text($content))));
            // 获取当前私信列表list的type、min_max
            $list_map['list_id']       = $list_id;
            $list_info = M('message_list')->field('type,member_num,min_max')->where($list_map)->select();
            if (1 == $list_info['type']) { // 一对一
                $list_data['member_num'] = 2;
                // 重置最新记录
                M('message_list')->save($list_data);
                // 重置其他成员信息
                if ($list_info['member_num'] < 2) {
                    $member_data = array(
                        'list_id' => $list_id,
                        'member'  => array_diff(explode('_', $list_info['min_max']), array($from_uid)),
                        'mtime'   => $time
                    );
                    $this->_addMessageMember($member_data, $from_uid);
                } else {
                    // 重置其他成员信息
                    $member_data['new']         = array('exp', '`new`+1');
                    $member_data['message_num'] = array('exp', '`message_num`+1');
                    $member_data['list_ctime']  = $time;
                    M('message_member')->where("`list_id`={$list_id} AND `member_uid`!={$from_uid}")->save($member_data);
                }
            } else { // 多人
                // 重置最新记录
                M('message_list')->save($list_data);
                // 重置其他成员信息
                $member_data['new']         = array('exp', '`new`+1');
                $member_data['message_num'] = array('exp', '`message_num`+1');
                $member_data['list_ctime']  = $time;
                M('message_member')->where("`list_id`={$list_id} AND `member_uid`!={$from_uid}")->save($member_data);
            }
            // 重置回复者的成员信息
            $from_data['message_num'] = array('exp', '`message_num`+1');
            $from_data['ctime']       = $time;
            $from_data['list_ctime']  = $time;
            M('message_member')->where("`list_id`={$list_id} AND `member_uid`={$from_uid}")->save($from_data);
            unset($from_data);
        }
        return $new_message_id;
    }

    /**
     * 直接删除私信（管理员）
     *
     * @param array|string $list_ids 多个私信ID可以组成数组，也可以用“,”分隔
     * @return boolean
     */
    public function deleteMessageList($list_ids) {
        if (!$list_ids) {
            return false;
        }
        $map['list_id']    = array('IN', $list_ids);
        return false !== M('message_content')->where($map)->delete()
               && false !== M('message_member')->where($map)->delete()
               && false !== M('message_list')->where($map)->delete();
    }

    /**
     * 用户删除会话
     *
     * @param int          $uid         用户ID
     * @param array|string $message_ids 多个会话ID可以组成数组，也可以用“,”分隔
     * @return boolean
     */
    public function deleteSessionById($member_uid, $message_ids) {
        $message_ids = intval($message_ids);
        $member_uid  = intval($member_uid);
        if (!$message_ids || !$member_uid) {
            return false;
        }
        $where = "`message_id`={$message_ids}";
        $list = M('message_content')->where($where)->field('`list_id`')->select();
        $res= M('message_content')->where($where . " AND `is_del`>0 AND `is_del`!={$member_uid}")->delete();
        if (false ==$res)
            if( false === M('message_content')->where($where)->setField('is_del',$member_uid)){
            	return false;
            }
        $member_map['list_id']    = $list[0]['list_id'];
        $member_map['member_uid'] = $member_uid;
        $res = M('message_member')->where($member_map)->setDec('message_num');     
        return $res;
    }

    /**
     * 一对一删除list同时标记session删除
     * @param
     */
    public function _deleteSessionByListId($member_uid, $list_ids){
        $member_uid  = intval($member_uid);
        if (!$list_ids || !$member_uid) {
            return false;
        }
        $list_ids = array_map('intval', is_array($list_ids) ? $list_ids : explode(',', $list_ids));
        $map['list_id'] = array('IN', $list_ids);
        $map['type']    = 1;
        $list_ids = M('message_list')->field('list_id')->where($map)->select();
        $data['list_id'] = array('in',implode(',', common('Array')->getSubByKey($list_ids, 'list_id')));
        $mm['list_id'] = $data['list_id'];
        $mm['is_del'] = array(array('gt',0),array('neq',$member_uid));
        $ms['list_id'] = $data['list_id'];
        $ms['is_del'] = array('eq',0);
        if (false === M('message_content')->where($mm)->delete() || 
        	false === M('message_content')->where($ms)->setField('is_del',$member_uid)) {
            return false;
        }
        return true;
    }

    /**
     * 获取私信成员
     *
     * @param $list_id 私信列表ID
     * @param $field   成员字段
     */
    public function getMessageMembers($list_id, $field = null){
        $list_id = intval($list_id);
        static $_members = array();
        if (!isset($_members[$list_id])) {
            $_members[$list_id] = M('message_member')->field($field)->where("`list_id`={$list_id}")->select();
        }
        return $_members[$list_id];
    }

    /**
     * 验证是否为私信成员
     *
     * @param $list_id     私信列表ID
     * @param $uid         用户ID
     * @param $show_detail 是否返回用户当前私信的详细状态
     */
    public function isMember($list_id, $uid, $show_detail = false){
        $list_id = intval($list_id);
        $uid     = intval($uid);
        $show_detail = $show_detail ? 1 : 0;
        static $_is_member = array();
        if (!isset($_is_member[$list_id][$uid][$show_detail])) {
            $map['list_id']    = $list_id;
            $map['member_uid'] = $uid;
            if ($show_detail) {
                $_is_member[$list_id][$uid][$show_detail] = M('message_member')->where($map)->select();
            } else {
                $_is_member[$list_id][$uid][$show_detail] = M('message_member')->getField('member_uid', $map);
            }
        }
        return $_is_member[$list_id][$uid][$show_detail];
    }

    /** 
     * 添加私信list
     *
     * @param $data content:私信内容，member:私信成员UID数组，mtime:当前时间
     * @param $from_uid 发布人UID
     */
    private function _addMessageList($data, $from_uid){
        if (!$data['content'] || !is_array($data['member']) || !$from_uid) {
            return false;
        }
        $list['from_uid'] = $from_uid;
        $list['title']    = $data['title'] ? common('Html')->text($data['title']) : common('Html')->text(common('Url')->getShort($data['content'],20));
        $list['member_num'] = count($data['member']);
        $list['type']     = in_array($data['type'], array(1, 2)) ? $data['type'] : (2 == $list['member_num'] ? 1 : 2);
        $list['min_max']  = $this->_getUidMinMax($data['member']);
        $list['mtime']    = $data['mtime'];
        $list['last_message']  = serialize(array(
            'from_uid' => $from_uid,
            'content'  => common('String')->keyWordFilter(common('Html')->text($data['content'], true))
        ));
        $list_map['type']    = $list['type'];
        $list_map['min_max'] = $list['min_max'];
        if (1 == $list['type'] && $list_id = M('message_list')->where($list_map)->getField('list_id')) {
            $list_map['list_id'] = $list_id;
            $_list['member_num']   = $list['member_num'];
            $_list['last_message'] = $list['last_message'];
            false === M('message_list')->where($list_map)->data($_list)->save() && $list_id = false;
        } else {
            $list_id = M('message_list')->data($list)->add();
        }
        return $list_id;
    }

    /** 
     * 添加私信member
     *
     * @param $data list_id:私信列表ID，member:私信成员UID数组，mtime:当前时间
     * @param $from_uid 发布人UID
     */
    private function _addMessageMember($data, $from_uid){
        if (!$data['list_id'] || !is_array($data['member']) || !$from_uid) {
            return false;
        }
        $member['list_id'] = $data['list_id'];
        $member['member_uid'] = '';
        $member['new']     = 0;
        $member['ctime']   = 0;
        $member['list_ctime'] = $data['mtime'];
        $members = array();
        foreach ($data['member'] as $k => $m) {
            $member['member_uid'] = $m;
            if ($m == $from_uid ) {
                $member['new'] = 0;
                $member['ctime'] = $data['mtime'];
            } else {
                $member['new'] = '`new`+1';
                $member['ctime'] = '`ctime`';
            }
            $members[] = '(' . implode(',', $member) . ')';
            unset($data['member'][$k]);
        }
        $members = implode(',', $members);
        $sql = "REPLACE INTO `{$this->tablePrefix}message_member`(`list_id`,`member_uid`,`new`,`ctime`,`list_ctime`) VALUES {$members}";
        return $this->query($sql);
    }

    /**
     * 添加私信message
     * @param array $data
     * @param int $from_uid
     */
    private function _addMessage($data, $from_uid){
        if (!$data['list_id'] || !$data['content'] || !$from_uid) {
            return false;
        }
        $message['list_id']  = $data['list_id'];
        $message['from_uid'] = $from_uid;
        $message['content']  = $data['content'];
        $message['is_del']   = 0;
        $message['mtime']    = $data['mtime'];
        return M('message_content')->data($message)->add();
    }

    private function _getUidMinMax($uids){
        sort($uids);
        return implode('_', $uids);
    }
    
    /**
     * 用户未读私信数
     *
     * @param int $uid 用户ID
     * @return array
     */
    public function getUnreadMessageCount($uid) {
    	$map['member_uid']  = intval($uid);
    	return intval(M('message_member')->where($map)->sum('new'));
    }
    
    /**
     * 未读评论数
     *
     * @param int $uid 用户ID
     * @return boolean
     */
    public function getUnreadCount($uid) {
    	$map = "(appuid={$uid} OR to_uid={$uid}) AND status>=0 AND status<>{$uid}";
    	return $this->where($map)->count();
    }
}
